package com.zn.socket;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by yinjiawei on 2018/7/12.
 */
public class WriterTask{
    private BufferedWriter bufferedWriter;
    //声明一个可变尺寸线程池
    private ExecutorService pool = Executors.newCachedThreadPool();
    private Socket socket = null;

    public WriterTask(Socket socket) throws IOException {
        this.bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        this.socket = socket;
    }

    /**
     * finishTask:(这里用一句话描述这个方法的作用). <br/>
     * TODO(这里描述这个方法适用条件 – 可选).<br/>
     * @throws IOException
     *
     */
    public void finish() throws IOException {
        if(bufferedWriter!=null && socket!=null)
        {
            if(!socket.isOutputShutdown())
            {
                socket.shutdownOutput();
            }
            bufferedWriter.close();
        }
    }


    public void send(String msg){
        //this.msg = msg;
        pool.execute(new Thread(() -> {
            try {
                //优化成线程池
                bufferedWriter.write(msg);
                bufferedWriter.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }));
//        new Thread(() -> {
//            try {
//                //优化成线程池
//                bufferedWriter.write(msg);
//                bufferedWriter.flush();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        });//.start();
    }
}
